package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Sound;
import com.itheima.service.mongo.SoundService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class SoundServiceImpl implements SoundService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存语音
     * @param sound 语音对象
     */
    @Override
    public void saveSound(Sound sound) {
        sound.setCreated(System.currentTimeMillis());
        mongoTemplate.save(sound);
    }

    /**
     * 随机获取一个语音
     * @return sound对象
     */
    @Override
    public Sound getRandomSound(Long loginUserId) {
        //查询除自己之外的语音
        Query query = new Query(Criteria.where("userId").ne(loginUserId));
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);
        //System.out.println(soundList);
        if (CollectionUtil.isNotEmpty(soundList)) {
            int count = RandomUtil.randomInt(soundList.size());
            return soundList.get(count);
        }
        return null;
    }
}
